<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品型号" prop="model">
        <el-input
          v-model="queryParams.model"
          placeholder="请输入产品型号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="进场时间" prop="enterTime">
        <el-date-picker
          v-model="queryParams.enterTime"
          clearable
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择进场时间"
        />
      </el-form-item>
      <el-form-item label="计划出场时间" prop="expectExitTime">
        <el-date-picker
          v-model="queryParams.expectExitTime"
          clearable
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择计划出场时间"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['order:order:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="queryBizTask"
        >导入订单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['order:order:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleStore"
        >入库</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['order:order:edit']"
          type="success"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleTesting"
        >生产</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['order:order:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="标识" align="center" prop="id" />
      <el-table-column label="客户名称" align="center" prop="customerName" />
      <el-table-column label="委托单号" align="center" prop="orderNo" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="产品数量" align="center" prop="quantity" />
      <el-table-column prop="palletCode" header-align="center" align="center" label="托盘编码" width="150">
      </el-table-column>
      <el-table-column label="进场时间" align="center" prop="enterTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.enterTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划出场时间" align="center" prop="expectExitTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expectExitTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_order_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button  v-if="scope.row.status === '1'" 
            v-hasPermi="['order:order:add']"
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleStore(scope.row)"
          >入库</el-button>
          <el-button   v-if="scope.row.status === '2'" 
            v-hasPermi="['order:order:edit']"
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleTesting(scope.row)"
          >生产</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改检测订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="form.customerName" placeholder="请输入客户名称" />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="产品型号" prop="model">
          <el-input v-model="form.model" placeholder="请输入产品型号" />
        </el-form-item>
        <el-form-item label="产品数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入产品数量" />
        </el-form-item>
        <el-form-item label="进场时间" prop="enterTime">
          <el-date-picker
            v-model="form.enterTime"
            clearable
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择进场时间"
          />
        </el-form-item>
        <el-form-item label="计划出场时间" prop="expectExitTime">
          <el-date-picker
            v-model="form.expectExitTime"
            clearable
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择计划出场时间"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 绑定检测订单对话框 -->
    <el-dialog :title="storeTitle" :visible.sync="storeOpen" width="700px" append-to-body>
      <el-form ref="storeForm" :model="form" :rules="storeRules" label-width="80px">
        <el-form-item label="订单标识" prop="id" v-if="false"></el-form-item>
        <el-form-item label="订单状态" prop="status" v-if="false"></el-form-item>
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="storeForm.customerName" readonly/>
        </el-form-item>
        <el-form-item label="委托单号" prop="orderNo">
          <el-input v-model="storeForm.orderNo" readonly/>
        </el-form-item>
        <el-form-item label="已绑托盘" prop="palletCode">
          <el-input v-model="storeForm.palletCode" placeholder="请输入托盘编码"/> 
        </el-form-item>
        <el-form-item label="添加托盘" prop="palletCodeAdd">
          <el-input v-model="storeForm.palletCodeAdd" placeholder="请扫码托盘编码" @keyup.enter.native="handleAddPallet"/>
        </el-form-item>
        <el-form-item label="中转库位">
              <el-select v-model="storeForm.positionCodes" multiple placeholder="请选择中转区库位">
                <el-option v-for="item in positionOptions" :key="item.code" :label="item.code" :value="item.code"></el-option>
              </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitStoreForm">确 定</el-button>
        <el-button @click="cancelStore">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrder, getOrder, testingOrder,  delOrder, addOrder, updateOrder, queryBizTask } from '@/api/order/order'

import { listPallet } from '@/api/order/pallet'

export default {
  name: 'Order',
  dicts: ['mes_order_status'],
  data() {
    return {
      // 表格直接绑定托盘数据
      pallets: [], // 保存绑定托盘数据
      showInput: '', // 用来判断是否显示哪个单元格
      oldData: {}, // 用来存修改前的数据
      currentData: {}, // 用来保存新的数据
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 检测订单表格数据
      orderList: [],
      
      // 仓位选项
      positionOptions: [],
      // 弹出层标题
      title: '',
      // 弹出绑定层标题
      storeTitle: '',
      // 是否显示弹出层
      open: false,
      storeOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerName: null,
        productName: null,
        model: null,
        quantity: null,
        enterTime: null,
        expectExitTime: null,
        creator: null,
        updater: null,
        deleted: null
      },
      // 查询参数
      queryPalletParams: {
        pageNum: 1,
        pageSize: 1000,
        status: 'Y'
      },
      // 表单参数
      form: {},
      // 表单参数
      storeForm: {},
      // 表单校验
      rules: {
      },
      // 表单校验
      storeRules: {
      }
    }
  },
  // 控制是否显示select下拉框
  tableDbEdit(row, column, event) {
    this.showInput = column.property + row.inboundId
    this.oldData[column.property] = row[column.property]
  },
  created() {
    this.getList()
  },
  methods: {
    handleUpdateRow(row) {
      row.palletEdit = true
      this.$forceUpdate()
    },
    handleCancelRow(row) {
      row.palletEdit = false
      this.$forceUpdate()
    },
    queryBizTask() {
      const taskReq = {}
      queryBizTask(taskReq).then(response => {
        this.$modal.msgSuccess('获取需求系统订单成功')
        this.open = false
        this.getList()
      }).catch(error => {
        console.error('获取需求系统订单失败:', error)
      })
    },
    handleSaveRow(row) {
      // 调用保存接口
      const id = row.id || this.ids
      getOrder(id).then(response => {
        this.form = response.data
        // 确保在获取到数据后再进行判断
        if (this.form.id != null) {
          this.form.palletCode = row.palletCode
          updateOrder(this.form).then(response => {
            this.$modal.msgSuccess('修改成功')
            this.open = false
            this.getList()
          }).catch(error => {
            console.error('更新订单失败:', error)
          })
        }
      }).catch(error => {
        console.error('获取订单信息失败:', error)
      })
    },
    /** 查询未使用的托盘列表 */
    getPallets() {
      listPallet(this.queryPalletParams).then(response => {
        this.pallets = response.rows
      })
    },
    // 当input失去光标后进行的操作
    async blurInput(row, name, value) {
      // 判断数据是否有所改变，如果数据有改变则调用修改接口
      if (this.oldData[name] != value) {
        row[name] = value
      }
      this.showInput = ''
      this.currentData = row
      if (name === 'palletCode') {
        this.getPallets(row)
      }
    },

    setPallets(row) {
      for (const index in this.pallets) {
        const item = this.pallets[index]
        if (row.palletCode === item.palletCode) {
          row.palletId = item.id
          return
        }
      }
    },

    /** 查询检测订单列表 */
    getList() {
      this.loading = true
      listOrder(this.queryParams).then(response => {
        this.orderList = (response.rows || []).map(v => {
          return {
            ...v,
            palletEdit: false
          }
        })
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.storeOpen = false
      this.reset()
    },
    // 取消按钮
    cancelStore() {
      this.storeOpen = false
      this.storeReset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        customerName: null,
        productName: null,
        model: null,
        quantity: null,
        enterTime: null,
        expectExitTime: null,
        creator: null,
        createTime: null,
        updater: null,
        updateTime: null,
        deleted: null
      }
      this.resetForm('form')
    },
    // 表单重置
    storeReset() {
      this.storeForm = { 
        customerName: null,
        orderNo: null
      }
      this.resetForm('storeForm')
    },
    //扫码添加托盘编码
    handleAddPallet() {
      const palletCodeAdd = this.storeForm.palletCodeAdd
      if (palletCodeAdd) {
        if(this.storeForm.palletCode) { 
          this.storeForm.palletCode += ',' + palletCodeAdd
        } else {
          this.storeForm.palletCode = palletCodeAdd
        }
        this.storeForm.palletCodeAdd = ''

      } else {
        this.$modal.msgWarning('请使用扫码枪扫码获取托盘编码')
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加检测订单'
    },
    /** 入库按钮操作 */
    handleStore(row) {
      const id = row.id || this.ids
      getOrder(id).then(response => {
        this.storeForm.id = response.data.id
        this.storeForm.status = response.data.status
        this.storeForm.customerName = response.data.customerName
        this.storeForm.orderNo = response.data.orderNo
        this.storeForm.palletCode = response.data.palletCode
        this.positionOptions = response.positions
        this.storeOpen = true
        this.storeTitle = '绑定托盘'
      })
    },   
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getOrder(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改检测订单'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 提交按钮 */
    submitStoreForm() {
      if(this.storeForm.status !== '1') {
        this.$modal.msgWarning('订单非待待入库状态，无法入库')
        return
      }
      this.$refs['storeForm'].validate(valid => {
        if (valid) {
          if (this.storeForm.id != null) {
            updateOrder(this.storeForm).then(response => {
              this.$modal.msgSuccess('订单入库成功')
              this.storeOpen = false
              this.getList()
            })
          }
        }
      })
    },
    /** 生产操作 */
    handleTesting(row) {      
      if(this.storeForm.status !== '2') {
        this.$modal.msgWarning('订单非待检测状态，无法生产')
        return
      }
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认对检测订单编号为"' + ids + '"进行生产？').then(function() {
        return testingOrder(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('提交生产成功')
      }).catch(() => {})
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除检测订单编号为"' + ids + '"的数据项？').then(function() {
        return delOrder(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('order/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
